<template>
    <div ref="chart" style="width: 100%; height: 400px"></div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, defineProps, ref, watch } from "vue";
import * as echarts from "echarts";

const props = defineProps<{ spendingRankData: any }>();
// 创建一个引用来绑定 DOM 元素
const chart = ref(null);
let spendingAmountChart: echarts.ECharts | null = null;

// 注册生命周期钩子
onBeforeUnmount(() => {
    if (spendingAmountChart) {
        window.removeEventListener("resize", resizeChart);
        spendingAmountChart.dispose();
        spendingAmountChart = null; // 清除引用
    }
});

const resizeChart = () => {
    spendingAmountChart?.resize();
};

const initChart = () => {
    // 先销毁已有实例，避免重复初始化
    if (spendingAmountChart) {
        spendingAmountChart.dispose();
    }

    spendingAmountChart = echarts.init(chart.value);

    // 预处理数据：倒序排列，并截断 tradeDescription 长度
    const processedData = [...props.spendingRankData]
        .sort((a, b) => a.amount - b.amount)
        .map(item => ({
            ...item,
            tradeDescriptionProcess: item.tradeDescription.length > 10
                ? item.tradeDescription.slice(0, 10) + '...'
                : item.tradeDescription
        }));

    const option = {
        title: {
            text: "单笔消费金额排名",
        },
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow",
            },
            formatter: function (params: any) {
                let result = ` `;
                params.forEach((item: any) => {
                    const data = props.spendingRankData.sort((a:any, b:any) => a.amount - b.amount)[item.dataIndex];
                    result += `<br/>${data.counterParty}: ${data.tradeDescription} - ¥${item.value}`;
                });
                return result;
            },
        },
        legend: {},
        grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
        },
        xAxis: {
            type: "value",
            boundaryGap: [0, 0.01],
        },
        yAxis: {
            type: "category",
            data: processedData.map((item: any) => item.tradeDescriptionProcess),
        },
        series: [
            {
                name: "",
                type: "bar",
                data: processedData.map((item: any) => item.amount),
            },
        ],
    };

    spendingAmountChart.setOption(option);

    window.addEventListener("resize", resizeChart);
};

onMounted(initChart);

watch(() => props.spendingRankData, initChart, { deep: true });
</script>



<style scoped>
/* 样式可以根据需要调整 */
</style>
